var over = 0;
var action = 0;
var limit = 15;   // 每页默认显示15行数据
var arrStyleNo = [];
var arrSuitSize = [];

var thisPage = {
    first: 0,
    // 初始化页面
    OnPageLoad: function () {
        // 取得款号（各个子款号）
        arrStyleNo = parent.$("#SuitStyleNo").val().split("/");

        $("#grid__wrapper_lines").hide();
        // 设置尺码表头
        thisPage.SetSizeTableHeader();
        $("#wizard").scrollable({
            onBeforeSeek: function (event, i) {
                if (parseInt(i) === 1) {
                    let n = $("input[type='checkbox'][name='_check_row_colour']:checked").length;
                    if (parseInt(n) <= 0) {
                        ShowErrorMessagePanel('请设置颜色。');
                        $(".error-msg").css({top: '10px'});
                        return false;
                    }
                }
                if (parseInt(i) === 2) {
                    let success = CheckSizeInput();
                    if (!success)
                        return false;

                    let n = $("input[type='checkbox'][name='_check_row_size']:checked").length;
                    if (parseInt(n) <= 0) {
                        ShowErrorMessagePanel('请设置尺码。');
                        $(".error-msg").css({top: '10px'});
                        return false;
                    }
                }
                if (parseInt(i) === 3) {
                    dateHandler.CheckDate();
                    if (parseInt(dateHandler.OverFlag) === 0) {
                        ShowErrorMessagePanel('交付日期没有经过确认。');
                        $(".error-msg").css({top: '10px'});
                        return false;
                    }
                }
                if (parseInt(i) === 4) {
                    if (parseInt(destinationHandler.OverFlag) === 0) {
                        ShowErrorMessagePanel('发货目的地没有经过确认。');
                        $(".error-msg").css({top: '10px'});
                        return false;
                    }
                }
            }
        });

        setTimeout(function () {
            $('#loading').hide();
        }, 300);
    },
    SetRowStatus: function (self) {
        let $row = self.parent().parent().parent();
        if (self.is(":checked") === true) {
            $row.addClass("row__selected");
        } else {
            $row.removeClass("row__selected");
        }
    },
    SetSizeTableHeader: function () {
        let content = '';
        // step1: 清空尺码设置的表头以及表格内容
        $("#tabHeader02 tbody").empty();
        $("#tabData02 tbody").empty();

        // step2: 设置列宽度
        $("#tabHeader02 colgroup").empty();
        $("#tabData02 colgroup").empty();
        content += '<col style="width: 36px;" />';
        content += '<col style="width: 36px;" />';
        content += '<col style="width: 36px;" />';
        for (let i = 0; i < arrStyleNo.length - 1; i++) {
            content += '<col style="width: 240px;" />';
        }
        content += '<col />';
        $("#tabData02 colgroup").append(content);
        content += '<col style="width: 18px;" />';
        $("#tabHeader02 colgroup").append(content);

        // step3: 设置表头
        content = '';
        $("#tabHeader02 thead tr").empty();
        content += '<th><label class="btn" for="CheckAllSize" style="margin-left:7px;"><input id="CheckAllSize" type="checkbox" onclick="sizeHandler.DoCheckAll($(this));" /><i></i><span></span></label></th>';
        content += '<th style="text-align:center;">#</th>';
        content += '<th style="text-align:center;">删除</th>';
        if (arrStyleNo.length > 0) {
            for (let i = 0; i < arrStyleNo.length; i++) {
                content += '<th class="editable__column">' + '尺码（' + arrStyleNo[i] + '）</th>';
            }
        }
        content += '<th></th>';
        $("#tabHeader02 thead tr").append(content);
    }
};

//-----------------------------------------------------------------------------
// 颜色处理部分
//-----------------------------------------------------------------------------
var colourHandler = {
    numCheckbox: 0,
    DoChoiceColour: function () {
        parent.showModal(1095, 538, '选择颜色', parent.basePath + '/master/colour/choice.html?flag=1', null,
                function ($dialog) {
                    let _exist = $.inArray($dialog, parent.arrDialog);
                    if (_exist >= 0) {
                        parent.arrDialog.splice($.inArray($dialog, parent.arrDialog), 1);
                    }
                    // 做列表选择设置
                    if (parent.choice_success) {
                        colourHandler.AddColourDataToTable(parent.arrChoice[0]);
                    }
                    // 清空数组
                    parent.arrChoice.splice(0, parent.arrChoice.length);
                    parent.choice_success = false;
                });
    },
    // 构建颜色选择数据列表
    AddColourDataToTable: function (result) {
        if (result === null)
            return false;

        let content = '';
        if (result.length > 0) {
            for (let i = 0; i < result.length; i++) {
                let id = result[i].colourId; // 颜色id
                let sequence = i + 1;
                content += '<tr _mash_id="' + id + '">';
                content += '<td style="padding-left:9px;"><label class="btn" for="R-C-' + id + '"><input id="R-C-' + id + '" name="_check_row_colour" type="checkbox" onclick="colourHandler.DoCheckRow($(this));" value="' + id + '"/><i></i><span></span></label></td>';
                content += '<td style="text-align:center;">' + sequence + '</td>';
                content += '<td class="column__action"><span title="删除" class="trash" onclick="colourHandler.DeleteRow($(this));"><i class="fa-all fa-trash-o fa-1"></i></span></td>';
                content += '<td>' + result[i].colourNumber + '</td>';
                content += '<td>' + formatNullData(result[i].colourCnName) + '</td>';
                content += '<td>' + formatNullData(result[i].colourJpName) + '</td>';
                content += '<td>' + formatNullData(result[i].colourEnName) + '</td>';
                content += '</tr>';
                $("#tabData01 tbody").append(content);
                content = '';
            }
        }
        setOneTableRowColor("tabData01");
        SetSlaveTableHeight01();

        // 拖动表格行改变显示顺序
        $("#tabData01 tbody").wxdragsort({
            dragWrapper: $("#tabData01"),
            placeHolderWrapper: $("#divD1"),
            parentobj: $("#tabData01"),
            dragColumnIndex: 1,
            dragEnd: function () {
                colourHandler.ResetRowsNo();
                $("input[type='checkbox'][name='_check_row_colour']:checked").each(function () {
                    thisPage.SetRowStatus($(this));
                });
            }
        });

        colourHandler.numCheckbox = $("#tabData01 tbody tr").length;  // 设置选择行数
        colourHandler.ResetRowsNo();

        $("#CheckAllColour").click();
    },
    // 重新设置行号
    ResetRowsNo: function () {
        let i = 1;
        $("#tabData01 tbody tr").each(function () {
            $(this).find('td').eq(1).text(i);
            i = i + 1;
        });
    },
    // 选择全部或者全部清除
    DoCheckAll: function (self) {
        if (self.is(":checked") === true) {
            $("input[type='checkbox'][name='_check_row_colour']").each(function () {
                $(this).prop('checked', true);
                thisPage.SetRowStatus($(this));
            });
        } else {
            $("input[type='checkbox'][name='_check_row_colour']").each(function () {
                $(this).prop("checked", false);
                thisPage.SetRowStatus($(this));
            });
        }
    },
    // 选择一行
    DoCheckRow: function (self) {
        let n = $("input[type='checkbox'][name='_check_row_colour']:checked").length;
        if (n < colourHandler.numCheckbox) {
            $("#CheckAllColour").prop("checked", false);
        } else {
            $("#CheckAllColour").prop("checked", true);
        }
        thisPage.SetRowStatus(self);
    },
    DeleteRow: function ($self) {
        let _currRow = $self.parent().parent();
        //var _check_box = _currRow.find("td").eq(0).children("input[type='checkbox']").eq(0);
        parent.showModal(333, 140, '删除确认', '', null, null, 1, '请问，确定要删除当前行吗？',
                function ($dialog) {
                    let _exist = $.inArray($dialog, parent.arrDialog);
                    if (_exist >= 0) {
                        parent.arrDialog.splice($.inArray($dialog, parent.arrDialog), 1);
                    }
                    _currRow.remove();
                    colourHandler.numCheckbox = $("#tabData01 tbody tr").length;
                    if ($("input[type='checkbox'][name='_check_row_colour']:checked").length === $("#tabData01 tbody tr").length) {
                        $("#CheckAllColour").prop("checked", true);
                    } else {
                        $("#CheckAllColour").prop("checked", false);
                    }
                    setOneTableRowColor("tabData01");
                    SetSlaveTableHeight01();
                    colourHandler.ResetRowsNo();
                });
    }
};

//-----------------------------------------------------------------------------
// 尺码处理部分
//-----------------------------------------------------------------------------
var sizeHandler = {
    numCheckbox: 0,
    DoChoiceSize: function () {
        parent.showModal(1095, 538, '选择尺码', parent.basePath + '/master/size/choice.html?flag=1', null,
                function ($dialog) {
                    let _exist = $.inArray($dialog, parent.arrDialog);
                    if (_exist >= 0) {
                        parent.arrDialog.splice($.inArray($dialog, parent.arrDialog), 1);
                    }
                    // 做列表选择设置
                    if (parent.choice_success) {
                        // 根据选择构建尺码数据
                        sizeHandler.AddSizeDataToTable(parent.arrChoice[0]);
                    }
                    // 清空数组
                    parent.arrChoice.splice(0, parent.arrChoice.length);
                    parent.choice_success = false;
                });
    },
    // 构建尺码选择数据列表
    AddSizeDataToTable: function (result) {
        if (result === null)
            return false;

        let content = '';
        if (result.length > 0) {
            for (let i = 0; i < result.length; i++) {
                let id = result[i].sizeId; // 尺码id
                let sequence = i + 1;
                content += '<tr>';
                content += '<td style="padding-left:9px;"><label class="btn" for="R-S-' + id + '"><input id="R-S-' + id + '" name="_check_row_size" type="checkbox" onclick="sizeHandler.DoCheckRow($(this));" value="' + id + '"/><i></i><span></span></label></td>';
                content += '<td style="text-align:center;">' + sequence + '</td>';
                content += '<td class="column__action"><span title="删除" class="trash" onclick="sizeHandler.DeleteRow($(this));"><i class="fa-all fa-trash-o fa-1"></i></span></td>';
                content += '<td class="edited-cell" _mash_id="' + id + '">' + formatNullData(result[i].sizeName) + '</td>';
                if (arrStyleNo.length > 0) {
                    for (let j = 0; j < arrStyleNo.length - 1; j++) {
                        content += '<td class="edited-cell" _mash_id=""></td>';
                    }
                }
                content += '</tr>';
                $("#tabData02 tbody").append(content);
                content = '';
            }
        }
        setOneTableRowColor("tabData02");

        let id = "cellField";
        let name = "_cellField";
        $('#tabData02 tbody tr').find("td.edited-cell").click(function () {
            OnCellClickEvent($(this), id, name, 0);
        });

        sizeHandler.numCheckbox = $("#tabData02 tbody tr").length;  // 设置选择行数
        SetSlaveTableHeight02();
        sizeHandler.ResetRowsNo();

        $("#CheckAllSize").click();
    },
    // 重新设置行号
    ResetRowsNo: function () {
        let i = 1;
        $("#tabData02 tbody tr").each(function () {
            $(this).find('td').eq(1).html(i);
            i = i + 1;
        });
    },
    // 选择全部或者全部清除
    DoCheckAll: function (self) {
        if (self.is(":checked") === true) {
            $("input[type='checkbox'][name='_check_row_size']").each(function () {
                $(this).prop('checked', true);
                thisPage.SetRowStatus($(this));
            });
        } else {
            $("input[type='checkbox'][name='_check_row_size']").each(function () {
                $(this).prop("checked", false);
                thisPage.SetRowStatus($(this));
            });
        }
    },
    // 选择一行
    DoCheckRow: function (self) {
        let n = $("input[type='checkbox'][name='_check_row_size']:checked").length;
        if (n < sizeHandler.numCheckbox) {
            $("#CheckAllSize").prop("checked", false);
        } else {
            $("#CheckAllSize").prop("checked", true);
        }
        thisPage.SetRowStatus(self);
    },
    DeleteRow: function ($self) {
        let _currRow = $self.parent().parent();
        //var _check_box = _currRow.find("td").eq(0).children("input[type='checkbox']").eq(0);
        parent.showModal(333, 140, '删除确认', '', null, null, 1, '请问，确定要删除当前行吗？',
                function ($dialog) {
                    let _exist = $.inArray($dialog, parent.arrDialog);
                    if (_exist >= 0) {
                        parent.arrDialog.splice($.inArray($dialog, parent.arrDialog), 1);
                    }
                    _currRow.remove();
                    sizeHandler.numCheckbox = $("#tabData02 tbody tr").length;
                    if ($("input[type='checkbox'][name='_check_row_size']:checked").length === $("#tabData02 tbody tr").length) {
                        $("#CheckAllSize").prop("checked", true);
                    } else {
                        $("#CheckAllSize").prop("checked", false);
                    }
                    setOneTableRowColor("tabData02");
                    SetSlaveTableHeight02();
                    sizeHandler.ResetRowsNo();
                });
    }
};

//-----------------------------------------------------------------------------
// 交付日期处理
//-----------------------------------------------------------------------------
var dateHandler = {
    $currRow: null,
    dates: null,
    OverFlag: 0,
    // 构建交付日期
    BuildDateOfDeliveryDataTable: function (result) {
        if (result === null)
            return false;

        $("#tabData03 tbody").empty();
        let content = '';
        for (let i = 0; i < result.length; i++) {
            let sequence = i + 1;
            content += '<tr>';
            content += '<td style="text-align:center;">' + sequence + '</td>';
            content += '<td class="column__action"><span title="删除" class="trash" onclick="dateHandler.RemoveNewLine($(this));"><i class="fa-all fa-trash-o fa-1"></i></span></td>';
            content += '<td class="edited-cell">' + result[i] + '</td>';
            content += '</tr>';
            $("#tabData03 tbody").append(content);
            content = '';
        }
        setOneTableRowColor("tabData03");

        let id = "cellField";
        let name = "_cellField";
        $('#tabData02 tbody tr').find("td.edited-cell").click(function () {
            switch ($(this).index()) {
                case 2:
                    OnCellDateEditEvent($(this), id, name);
                    break;
            }
        });
    },
    // 添加新行以及新行的操作方式
    InsertNewLines: function () {
        let $newLine = $('<tr class="newLine" _mash_id="0">' +
                '    <td></td>' +
                '    <td class="column__action"><span title="删除" class="trash" onclick="dateHandler.RemoveNewLine($(this));""><i class="fa-all fa-trash-o fa-1"></i></span></td>' +
                '    <td class="edited-cell"></td>' +
                '</tr>');
        $('#tabData03 tbody').prepend($newLine);   // 加在前面
        setOneTableRowColor("tabData03");

        let id = "cellField";
        let name = "_cellField";
        $newLine.find("td.edited-cell").click(function () {
            OnCellDateEditEvent($(this), id, name);
        });

        dateHandler.OverFlag = 0;
        return $newLine;
    },
    RemoveNewLine: function ($self) {
        parent.showModal(333, 140, '删除确认', '', null, null, 1, '请问，确定要删除当前行吗？', function () {
            $self.parent().parent().remove();
            setOneTableRowColor("tabData03");

            dateHandler.OverFlag = 0;
        });
    },
    ConfirmDate: function () {
        $("#ButConfirmDate").focus();
        let success_01 = CheckDateGridInput();
        if (!success_01)
            return false;
        let arrDate = new Array();
        // 得到修改过数据
        $('#tabData03 tbody').find("tr").each(function (index) {
            let _DateOfDelivery = $.trim($(this).find('td').eq(2).text());
            _DateOfDelivery = new Date(Date.parse(_DateOfDelivery.replace(/-/g, "/")));
            // 统一设置日期格式
            arrDate.push(_DateOfDelivery.Format("yyyy-MM-dd"));
        });
        if (arrDate.length > 0) {
            if (isRepeat(arrDate)) {
                ShowErrorMessagePanel('错误，输入了重复日期。');
                $(".error-msg").css({top: '10px'});
                dateHandler.OverFlag = 0;
                return false;
            }
            dateHandler.SortDate(arrDate);
            dateHandler.BuildDateOfDeliveryDataTable(dateHandler.dates);
            dateHandler.OverFlag = 1;
        } else {
            ShowErrorMessagePanel('确认失败，没有填写交付日期。');
            $(".error-msg").css({top: '10px'});
            dateHandler.OverFlag = 0;
        }
    },
    CheckDate: function () {
        // 得到修改过数据
        $('#tabData03 tbody').find("tr").each(function (index) {
            if ($(this).find("td.dirty").length) {
                dateHandler.OverFlag = 0;
            }
        });
    },
    // 对日期进行排序
    SortDate: function (object_arr) {
        dateHandler.dates = object_arr.sort(
                function (a, b) {
                    return (new Date(a.replace(/-/g, '/')).getTime() - new Date(b.replace(/-/g, '/')).getTime());
                }
        );
    }
};

//-----------------------------------------------------------------------------
// 发货目的地处理部分
//-----------------------------------------------------------------------------
var destinationHandler = {
    _rows: 0,
    OverFlag: 0,
    // 重新设置行号
    ResetRowsNo: function () {
        let i = 1;
        $("#tabData04 tbody tr").each(function () {
            $(this).find('td').eq(0).text(i);
            i = i + 1;
        });
    },
    // 添加新行以及新行的操作方式
    InsertNewLines: function () {
        let $newLine = $('<tr class="newLine" _mash_id="0">' +
                '    <td style="text-align:center;"></td>' +
                '    <td class="column__action"><span title="删除" class="trash" onclick="destinationHandler.RemoveNewLine($(this));""><i class="fa-all fa-trash-o fa-1"></i></span></td>' +
                '    <td class="edited-cell"></td>' +
                '</tr>');
        $('#tabData04 tbody').prepend($newLine);   // 加在前面
        setOneTableRowColor("tabData04");
        destinationHandler._rows = destinationHandler._rows + 1;
        SetSlaveTableHeight04();

        let id = "cellField";
        let name = "_cellField";
        $newLine.find("td.edited-cell").click(function () {
            OnCellClickEvent($(this), id, name, 0);
        });

        destinationHandler.OverFlag = 0;

        // 拖动表格行改变显示顺序
        $("#tabData04 tbody").wxdragsort({
            dragWrapper: $("#tabData04"),
            placeHolderWrapper: $("#divD4"),
            parentobj: $("#tabData04"),
            dragColumnIndex: 0,
            dragEnd: function () {
                destinationHandler.ResetRowsNo();
            }
        });

        return $newLine;
    },
    RemoveNewLine: function ($self) {
        parent.showModal(333, 140, '删除确认', '', null, null, 1, '请问，确定要删除当前行吗？', function () {
            $self.parent().parent().remove();
            setOneTableRowColor("tabData04");

            destinationHandler.OverFlag = 0;
            destinationHandler._rows = destinationHandler._rows - 1;

            SetSlaveTableHeight04();
        });
    },
    ConfirmDestination: function () {
        $("#ButConfirmDestinatione").focus();
        let success_01 = CheckDestinationGridInput();
        if (!success_01)
            return false;
        $('#tabData04 tbody').find("tr").each(function (index) {
            $(this).find("td").eq(0).text(index + 1);
        });
        destinationHandler.OverFlag = 1;
    }
};

//-----------------------------------------------------------------------------
// 明细分配处理部分
//-----------------------------------------------------------------------------
var memoHandler = {
    $currRow: null,
    CreateInputTable: function () {
        let content = '';
        // step1: 首先设置列宽度
        $("#tabHeader05 colgroup").empty();
        $("#tabData05 colgroup").empty();
        content += '<col style="width: 36px;" />';
        content += '<col style="width: 70px;" />';
        content += '<col style="width: 140px;" />';
        content += '<col style="width: 200px;" />';
        content += '<col style="width: 44px;" />';
        if ($("#tabData04").find("tr").length > 0) {
            for (let i = 0; i < $("#tabData04").find("tr").length; i++) {
                for (let j = 0; j < dateHandler.dates.length; j++) {
                    content += '<col />';
                }
            }
        } else {
            for (let i = 0; i < dateHandler.dates.length; i++) {
                content += '<col />';
            }
        }
        $("#tabData05 colgroup").append(content);
        content += '<col style="width: 18px;" />';
        $("#tabHeader05 colgroup").append(content);

        content = '';
        //step2: 设置表头
        if ($("#tabData04").find("tr").length > 0) {
            $("#tabHeader05 thead").empty();
            content += '<tr>';
            content += '<th style="text-align:center;" class="report" rowspan="2">删除</th>';
            content += '<th class="report" rowspan="2">色号</th>';
            content += '<th class="report" rowspan="2">颜色</th>';
            content += '<th class="report" rowspan="2">尺码</th>';
            content += '<th class="editable-column report" rowspan="2">样品数</th>';
            for (let i = 0; i < $("#tabData04").find("tr").length; i++) {
                content += '<th class="cell_01" style="text-align:center;" colspan="' + dateHandler.dates.length + '">' + $("#tabData04").find("tr").eq(i).find("td").eq(2).text() + '</th>';
            }
            content += '<th class="report" rowspan="2"></th>';
            content += '</tr>';
            $("#tabHeader05 thead").append(content);
            content = '<tr>';
            for (let j = 0; j < $("#tabData04").find("tr").length; j++) {
                for (let i = 0; i < dateHandler.dates.length; i++) {
                    content += '<th class="cell_02" style="text-align:center;" class="editable__column">' + dateHandler.dates[i] + '</th>';
                }
            }
            content += '</tr>';
            $("#tabHeader05 thead").append(content);
        } else {
            $("#tabHeader05 thead").empty();
            content += '<tr>';
            content += '<th style="text-align:center;">删除</th>';
            content += '<th>色号</th>';
            content += '<th>颜色</th>';
            content += '<th>尺码</th>';
            content += '<th class="editable-column">样品数</th>';
            for (let i = 0; i < dateHandler.dates.length; i++) {
                content += '<th class="editable-column">' + dateHandler.dates[i] + '</th>';
            }
            content += '<th></th>';
            content += '</tr>';
            $("#tabHeader05 thead").append(content);
        }

        // step3: 设置表格内容
        content = '';
        $("#tabData05 tbody").empty();
        let index = 0;
        $("input[type='checkbox'][name='_check_row_colour']:checked").each(function (indexColour) {
            let $rowColour = $(this).parent().parent().parent();
            let _colourId = $(this).val();                          // 颜色ID
            let _colourNumber = $rowColour.find('td').eq(3).text(); // 色号
            let _colourName = $rowColour.find('td').eq(4).text();   // 颜色中文名            
            $("input[type='checkbox'][name='_check_row_size']:checked").each(function (indexSize) {
                index += 1;
                content += '<tr>';
                content += '<td class="column__action"><span title="删除" class="trash" onclick="memoHandler.RemoveLine($(this));"><i class="fa-all fa-trash-o fa-1"></i></span></td>';
                if (index > 1) {
                    let _prevColourId = $("#tabData05 tbody tr").last().find("td").eq(1).attr("_colour_id");
                    if (_colourId === _prevColourId) {
                        content += '<td style="border-bottom:none;" _colour_id="' + _colourId + '"></td>';
                        content += '<td style="border-bottom:none;"></td>';
                    } else {
                        content += '<td style="border-top:1px solid #c6c3bd; border-bottom:none;" _colour_id="' + _colourId + '">' + _colourNumber + '</td>';
                        content += '<td style="border-top:1px solid #c6c3bd; border-bottom:none;">' + _colourName + '</td>';
                    }
                } else {
                    content += '<td style="border-bottom:none;" _colour_id="' + _colourId + '">' + _colourNumber + '</td>';
                    content += '<td style="border-bottom:none;">' + _colourName + '</td>';
                }
                let _suitSizeName = '';
                let _suiteSizeMemo = [];     // 对应色的每款的尺码
                if (arrStyleNo.length > 0) {
                    for (let j = 0; j < arrStyleNo.length; j++) {
                        _suitSizeName += ($.trim($(this).parent().parent().parent().find('td').eq(3 + j).text())).toUpperCase() + "-";
                        let item = {};
                        item['productId'] = parent._InstancePageHeader.GetSuitProductId(j);
                        item['sizeName'] = ($.trim($(this).parent().parent().parent().find('td').eq(3 + j).text())).toUpperCase();  // 注意将尺码名变成大写，然后与数据库做对比
                        _suiteSizeMemo.push(item);
                    }
                }
                _suitSizeName = _suitSizeName.substring(0, _suitSizeName.length - 1);
                content += '<td _mash_suiteSizeMemo=\'' + JSON.stringify(_suiteSizeMemo) + '\'>' + _suitSizeName + '</td>';  // 尺码，注意将数组转为字符串
                content += '<td class="edited-cell"></td>';      // 样品数
                if ($("#tabData04").find("tr").length > 0) {
                    for (let j = 0; j < $("#tabData04").find("tr").length; j++) {
                        for (let i = 0; i < dateHandler.dates.length; i++) {
                            content += '<td class="edited-cell"></td>';
                        }
                    }
                } else {
                    for (let i = 0; i < dateHandler.dates.length; i++) {
                        content += '<td class="edited-cell"></td>';
                    }
                }
                content += '</tr>';
                $("#tabData05 tbody").append(content);
                content = '';
            });
        });
        setOneTableRowColor("tabData05");
        SetSlaveTableHeight05();

        let id = "cellField";
        let name = "_cellField";
        $('#tabData05 tbody tr').find("td.edited-cell").click(function () {
            OnCellClickEvent($(this), id, name, 0);
        });

        $("#grid__wrapper_lines").show();
    },
    RemoveLine: function ($self) {
        let _memo_row = $self.parent().parent();
        parent.showModal(333, 140, '删除确认', '', null, null, 1, '请问，确定要删除当前行吗？',
                function () {
                    let _currColourId = _memo_row.find("td").eq(1).attr("_colour_id");
                    // 如果是第一行，并且有相同的下一行
                    if ((_memo_row.index() === 0) && (_memo_row.next().length > 0)) {
                        let _nextColourId = _memo_row.next().find("td").eq(1).attr("_colour_id");
                        if (_currColourId === _nextColourId) {
                            _memo_row.next().find("td").eq(1).text(_memo_row.find("td").eq(1).text());
                            _memo_row.next().find("td").eq(2).text(_memo_row.find("td").eq(2).text());
                        }
                    }
                    // 不是表格第一行
                    if (_memo_row.index() > 0) {
                        let _prevColourId = _memo_row.prev().find("td").eq(1).attr("_colour_id");
                        // 是颜色起头第一行
                        if (_currColourId !== _prevColourId) {
                            if (_memo_row.next().length > 0) {
                                let _nextColourId = _memo_row.next().find("td").eq(1).attr("_colour_id");
                                if (_currColourId === _nextColourId) {
                                    _memo_row.next().find("td").eq(1).text(_memo_row.find("td").eq(1).text());
                                    _memo_row.next().find("td").eq(2).text(_memo_row.find("td").eq(2).text());
                                    _memo_row.next().find("td").eq(1).css({"border-top": "1px solid #c6c3bd"});
                                    _memo_row.next().find("td").eq(2).css({"border-top": "1px solid #c6c3bd"});
                                }
                            }
                        }
                    }
                    _memo_row.remove();
                    _memo_row = null;

                    setOneTableRowColor("tabData05");
                    SetSlaveTableHeight05();

                    // 设置第一行
                    $("#tabData05 tbody tr").eq(0).find("td").eq(1).css({"border-top": "none"});
                    $("#tabData05 tbody tr").eq(0).find("td").eq(2).css({"border-top": "none"});
                });
    },
    // 得到要保存的数据
    GetLinesData: function () {
        let params = {};
        let itemList = [];
        // 得到修改过数据
        $('#tabData05 tbody').find("tr").each(function () {
            let rowEntity = {};
            let _colourId = $.trim($(this).find('td').eq(1).attr("_colour_id"));                       // 颜色
            let _suiteSizeMemo = JSON.parse($(this).find('td').eq(3).attr('_mash_suiteSizeMemo'));     // 对应色的每款的尺码 
            let _sampleQuantity = $.trim($(this).find('td').eq(4).text());                             // 样品数
            let _schemaMemo = [];                                                                      // 按日期的分配数
            let _destinationMemo = [];                                                                 // 发货目的地
            if ($("#tabData04").find("tr").length > 0) {
                for (let j = 0; j < $("#tabData04").find("tr").length; j++) {
                    let entity = {};
                    entity['headerId'] = parseInt(parent.$("#HeaderId").val());
                    entity['orderNo'] = parseInt($.trim($("#tabData04").find("tr").eq(j).find("td").eq(0).text()));
                    entity['destination'] = $.trim($("#tabData04").find("tr").eq(j).find("td").eq(2).text());
                    entity['createdBy'] = parseInt(parent.$("#UserId").val());
                    entity['updatedBy'] = parseInt(parent.$("#UserId").val());
                    _destinationMemo.push(entity);

                    for (let i = 0; i < dateHandler.dates.length; i++) {
                        let item = {};
                        item['headerId'] = parseInt(parent.$("#HeaderId").val());
                        item['destination'] = $.trim($("#tabData04").find("tr").eq(j).find("td").eq(2).text());
                        item['deliveryDate'] = dateHandler.dates[i];
                        item['quantity'] = ($.trim($(this).find('td').eq(5 + j * dateHandler.dates.length + i).text()) === '') ? 0 : $.trim($(this).find('td').eq(5 + j * dateHandler.dates.length + i).text());
                        _schemaMemo.push(item);
                    }
                }
            } else {
                for (let i = 0; i < dateHandler.dates.length; i++) {
                    let item = {};
                    item['headerId'] = parseInt(parent.$("#HeaderId").val());
                    item['destination'] = null;
                    item['deliveryDate'] = dateHandler.dates[i];
                    item['quantity'] = ($.trim($(this).find('td').eq(5 + i).text()) === '') ? 0 : $.trim($(this).find('td').eq(5 + i).text());
                    _schemaMemo.push(item);
                }
            }

            // 设置每行的数据
            rowEntity['headerId'] = parent.$("#HeaderId").val();
            rowEntity['suitStyleNo'] = parent.$("#SuitStyleNo").val();
            rowEntity['colourId'] = _colourId;
            rowEntity['sampleQuantity'] = _sampleQuantity === '' ? 0 : _sampleQuantity;
            rowEntity['schemaMemo'] = _schemaMemo;
            rowEntity['destinationMemo'] = _destinationMemo;
            rowEntity['suiteSizeMemo'] = _suiteSizeMemo;
            rowEntity['createdBy'] = parent.$("#UserId").val();
            rowEntity['updatedBy'] = parent.$("#UserId").val();

            itemList.push(rowEntity);
        });

        let _linesColourOrder = [];
        $("input[type='checkbox'][name='_check_row_colour']:checked").each(function () {
            let item = {};
            let $row = $(this).parent().parent().parent();
            let _colourId = $row.attr("_mash_id");
            let _orderNo = $row.find("td").eq(1).text();

            item['HeaderId'] = parseInt(parent.$("#HeaderId").val());
            item['ColourId'] = parseInt(_colourId);
            item['OrderNo'] = parseInt(_orderNo);
            item['CreatedBy'] = parseInt(parent.$("#UserId").val());
            item['UpdatedBy'] = parseInt(parent.$("#UserId").val());

            _linesColourOrder.push(item);
        });
        params['LinesColourOrder'] = _linesColourOrder;
        params['LinesList'] = itemList;

        return JSON.stringify(params);
    },
    DoSave: function () {
        $("#ButSaveLines").focus();

        //step 1、进行页面验证，失败则返回
        let success_01 = CheckGrid05Input();
        if (!success_01)
            return;

        //step 2、执行处理
        $.ajax({
            type: "POST",
            url: parent.basePath + "/trade/production_instruction/lines/insert.html",
            timeout: 30 * 1000,
            data: memoHandler.GetLinesData(),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function () {
            }
        }).done(function (data) {
            if ($.isEmptyObject(data) === false) {
                $('#tabData05 tbody').find("td.dirty").removeClass("dirty");
                // 设置交付日期
                parent._InstancePageHeader.SetScheduleNode(data.ScheduleNode);
                // 设置发送目的地
                parent._InstancePageHeader.SetDestinationNode(data.DestinationNode);
                // 显示明细数据scheduleNode
                parent._InstancePageLines.BuildDataTable(data.LinesList);
                // 更新合同数、样品数
                parent.$("#TotalQuantity").val(data.SumQuantity.quantity);
                parent.$("#SampleQuantity").val(data.SumQuantity.samplequantity);

                parent.ShowSuccessMessagePanel("增加成功。");
            }
            closePopupWnd();
        }).fail(function (data) {
            ajaxError(data, 1);
            $(".error-msg").css({top: '10px'});
        }).always(function ( ) {
        });
    }
};

//-----------------------------------------------------------------------------
// 页面初始化
//-----------------------------------------------------------------------------
function onPageReady() {
    thisPage.OnPageLoad();
}

// 画面大小或者位置移动
function onPageResize() {
    let _h = $(window).height();
    let _w = $(window).width();

    $("#wizard").css({width: _w, height: _h});
    $("div.page").css({width: _w, height: _h});

    over = 1;
}

// 根据窗口大小设置明细列表的高度（自适应高度）
function SetSlaveTableHeight01() {
    let h = $(window).height();
    let _tabTop = $("#grid__wrapper_colour").offset().top + 26;   // 用于随着窗口变化，下面明细高度随之变化的一个节点
    //$("#test").remove();
    //$(document.body).append('<div id="test" style="background:red;width:100%;position:absolute; top:' + _tabTop + 'px;display:block;height:5px;z-index:10000" />');
    let _rc = Math.floor((h - _tabTop - 10) / 25);
    let _dh = _rc * 25;
    let _rowH = $("#tabData01 tbody tr").length * 25; // 计算行高
    _dh = (_rowH >= _dh) ? _dh : _rowH;

    $("#divD1").css({"max-height": _dh, height: _dh});
}

// 根据窗口大小设置明细列表的高度（自适应高度）
function SetSlaveTableHeight02() {
    let h = $(window).height();
    let _tabTop = $("#grid__wrapper_size").offset().top + 26;   // 用于随着窗口变化，下面明细高度随之变化的一个节点
    //$("#test").remove();
    //$(document.body).append('<div id="test" style="background:red;width:100%;position:absolute; top:' + _tabTop + 'px;display:block;height:5px;z-index:10000" />');
    let _rc = Math.floor((h - _tabTop - 10) / 25);
    let _dh = _rc * 25;
    let _rowH = $("#tabData02 tbody tr").length * 25; // 计算行高
    _dh = (_rowH >= _dh) ? _dh : _rowH;

    $("#divD2").css({"max-height": _dh, height: _dh});
}

// 根据窗口大小设置明细列表的高度（自适应高度）
function SetSlaveTableHeight04() {
    let h = $(window).height();
    let _tabTop = 121;
    let _rc = Math.floor((h - _tabTop - 10) / 25);
    let _dh = _rc * 25;
    let _rowH = $("#tabData04 tbody tr").length * 25; // 计算行高
    _dh = (_rowH >= _dh) ? _dh : _rowH;

    $("#divD4").css({"max-height": _dh, height: _dh});
}

// 根据窗口大小设置明细列表的高度（自适应高度）
function SetSlaveTableHeight05() {
    let h = $(window).height();
    let _tabTop = 121;
    let _rc = 0;
    if ($("#tabData04").find("tr").length > 0) {
        _rc = Math.floor((h - _tabTop - 55) / 25);
    } else {
        _rc = Math.floor((h - _tabTop - 30) / 25);
    }
    let _dh = _rc * 25;
    let _rowH = $("#tabData05 tbody tr").length * 25; // 计算行高
    _dh = (_rowH >= _dh) ? _dh : _rowH;

    $("#divD5").css({"max-height": _dh, height: _dh});
}
//-----------------------------------------------------------------------------
// 验证函数
//-----------------------------------------------------------------------------

// 验证尺码信息（是否填入）
function CheckSizeInput() {
    $('#tabData02 tbody').find("tr").each(function () {
        let $row = $(this);
        if (arrStyleNo.length > 0) {
            for (let i = 0; i < arrStyleNo.length - 1; i++) {
                let _size = $.trim($(this).find('td').eq(i + 4).text());
                if (_size !== '') {
                    GridCheckSuccessHandle($row, i + 4);
                } else {
                    GridCheckErrHandle($row, i + 4, '请输入对应款号的尺码。');

                }
            }
        }
    });
    if ($('#tabData02 tbody').find('td.error').length > 0) {
        ShowErrorMessagePanel('对不起，填写的数据有错误。');
        $(".error-msg").css({top: '10px'});
        return false;
    } else {
        return true;
    }
}

// 验证输入日期
function CheckDateGridInput() {
    $('#tabData03 tbody').find("tr").each(function () {
        let $row = $(this);
        let _deliveryDate = $.trim($(this).find('td').eq(2).text());
        if (_deliveryDate !== '') {
            if (!validateCNDate(_deliveryDate)) {
                GridCheckErrHandle($row, 2, '请输入正确的日期。');
            } else {
                GridCheckSuccessHandle($row, 2);
            }
        } else {
            GridCheckErrHandle($row, 2, '请填写交付日期。');
        }
    });
    if ($('#tabData03 tbody').find('td.error').length > 0) {
        ShowErrorMessagePanel('对不起，填写的数据有错误。');
        $(".error-msg").css({top: '10px'});
        return false;
    } else {
        return true;
    }
}

// 验证发货地
function CheckDestinationGridInput() {
    $('#tabData04 tbody').find("tr").each(function () {
        let $row = $(this);
        let _destination = $.trim($(this).find('td').eq(2).text());
        if (_destination !== '') {
            GridCheckSuccessHandle($row, 2);
        } else {
            GridCheckErrHandle($row, 2, '请填写发货目的地。');
        }
    });
    if ($('#tabData04 tbody').find('td.error').length > 0) {
        ShowErrorMessagePanel('对不起，填写的数据有错误。');
        $(".error-msg").css({top: '10px'});
        return false;
    } else {
        return true;
    }
}

// 验证保存数据
function CheckGrid05Input() {
    $('#tabData05 tbody').find("tr").each(function () {
        let $row = $(this);
        let _sampleQuantity = $.trim($(this).find('td').eq(4).text());

        if (_sampleQuantity !== '') {
            if (!isNumber(_sampleQuantity)) {
                GridCheckErrHandle($row, 4, '请输入正确的数字。');
            } else {
                GridCheckSuccessHandle($row, 4);
            }
        }

        for (let i = 0; i < dateHandler.dates.length; i++) {
            let _quantity = $.trim($(this).find('td').eq(5 + i).text());
            if (_quantity !== '') {
                if (!isNumber(_quantity)) {
                    GridCheckErrHandle($row, 5 + i, '请输入正确的数字。');
                } else {
                    GridCheckSuccessHandle($row, 5 + i);
                }
            }
        }
    });
    if ($('#tabData05 tbody').find('td.error').length > 0) {
        ShowErrorMessagePanel('对不起，填写的数据有错误。');
        $(".error-msg").css({top: '5px'});
        return false;
    } else {
        return true;
    }
}
function GridCheckErrHandle($row, index, errMsg) {
    $row.find('td').eq(index).addClass("error");
    $row.find('td').eq(index).attr('title', errMsg);
}
function GridCheckSuccessHandle($row, index) {
    $row.find('td').eq(index).removeClass("error");
    $row.find('td').eq(index).attr('title', '');
}